import java.util.Arrays;

public class LeetCode566 {

    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(matrixReshape(new int[][]{{1, 2}, {3, 4}}, 2, 4)));
    }

    public static int[][] matrixReshape(int[][] mat, int r, int c) {
        if (mat.length * mat[0].length != r * c) {
            return mat;
        }

        int[][] res = new int[r][c];

        int m = mat.length;
        int n = mat[0].length;
        for (int rowIndex = 0; rowIndex < m; rowIndex++) {
            for (int columnIndex = 0; columnIndex < mat[rowIndex].length; columnIndex++) {
                res[(rowIndex * n + columnIndex) / c][(rowIndex * n + columnIndex) % c] = mat[rowIndex][columnIndex];
            }
        }

        return res;
    }
}
